package com.top.ruizhong.main.host

import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.material.tabs.TabLayout
import com.module.lemlin.base.BaseAbstractFragment
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.tbruyelle.rxpermissions3.RxPermissions
import com.top.ruizhong.R
import com.top.ruizhong.entity.VideoCateList
import com.top.ruizhong.main.video.VideoFragment
import com.top.ruizhong.mode.vm.VideoViewModel
import com.top.ruizhong.popup.VideoCategoryPopup
import com.top.ruizhong.popup.VideoDiscussPopup
import kotlinx.android.synthetic.main.fragment_main_recom.*
import java.lang.StringBuilder

class MainRecomFragment : ViewModeFragment<VideoViewModel>() {


    companion object {
        fun newInstance(): MainRecomFragment {
            return MainRecomFragment()
        }
    }

    private val videoCategoryPopup: VideoCategoryPopup by lazy {
        VideoCategoryPopup(context = requireContext(), onConfirmTotal = { _, _, videoCate ->
            val videoCateList: MutableList<VideoCateList> =
                mVideoCateListDefault.filter { it.id != -1 && it.id != -2 && it.id != videoCate.id }
                    .toMutableList()
            val cateIds = StringBuilder()
            videoCateList.forEach {
                cateIds.append(it.id).append(",")
            }
            cateIds.deleteCharAt((cateIds.length - 1))
            viewModel.videoSetCate(cateIds.toString(), videoCate, type = 2)
        }, onConfirmDefault = { _, _, videoCate ->
            val videoCateList: MutableList<VideoCateList> =
                mVideoCateListDefault.filter { it.id != -1 && it.id != -2 }.toMutableList()
            if (videoCateList.find { it.id == videoCate.id } != null)
                return@VideoCategoryPopup
            videoCateList.add(videoCate)
            val cateIds = StringBuilder()
            videoCateList.forEach {
                cateIds.append(it.id).append(",")
            }
            cateIds.deleteCharAt((cateIds.length - 1))
            viewModel.videoSetCate(cateIds.toString(), videoCate, type = 1)
        })
    }

    private val mVideoCateListDefault: MutableList<VideoCateList> = mutableListOf()
    private val mFragments: MutableList<Fragment> = mutableListOf()

    private val mVideoFragmentStatePagerAdapter: FragmentStatePagerAdapter by lazy {

        object : FragmentStatePagerAdapter(
            childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        ) {

            override fun getItem(position: Int): Fragment {
                val fragment: Fragment =
                    VideoFragment.newInstance(mVideoCateListDefault[position].id)
                mFragments.add(fragment)
                return fragment
            }

            override fun getCount(): Int {
                return mVideoCateListDefault.size
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return mVideoCateListDefault[position].name
            }

            override fun getItemPosition(`object`: Any): Int {
                return PagerAdapter.POSITION_NONE
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                super.destroyItem(container, position, `object`)
            }
        }
    }

    override val layoutResId: Int
        get() = R.layout.fragment_main_recom

    override fun viewModel(): VideoViewModel {
        return createViewModel()
    }

    override fun initView() {

        BarUtils.addMarginTopEqualStatusBarHeight(tabMainRecomCategory)
//        BarUtils.addMarginTopEqualStatusBarHeight(vpMainRecomVideo)

        ivMainRecomCategory.setOnClickListener {
            if (viewModel.videoCateTotalListLiveData.value == null)
                viewModel.videoCateTotalList()
            videoCategoryPopup.showPopupWindow()
        }

        tabMainRecomCategory.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) = Unit

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.customView = null
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                val text: TextView = TextView(context).apply {
                    setTextColor(ColorUtils.getColor(R.color.colorWhite))
                    textSize = 16f
                    gravity = Gravity.CENTER
                    paint.isFakeBoldText = true
                }
                text.text = tab?.text
                tab?.customView = text
            }
        })


        tabMainRecomCategory.setupWithViewPager(vpMainRecomVideo.apply {
            adapter = mVideoFragmentStatePagerAdapter
        })

    }

    override fun initData() {
        viewModel.videoDefaultCateList()
        viewModel.videoCateTotalList()
    }

    override fun initViewMode() {
        viewModel.videoCateDefaultListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                mVideoCateListDefault.addAll(it)
                mVideoFragmentStatePagerAdapter.notifyDataSetChanged()
                videoCategoryPopup.setFillDataCateListDefault(it)
            }
        })
        viewModel.videoCateTotalListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                videoCategoryPopup.setFillDataCateListTotal(it)
            }
        })

        viewModel.videoSetCateLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let { set ->
                set.videoCateList?.let {
                    if (set.type == 1) {
                        mVideoCateListDefault.add(it)
                    }
                    if (set.type == 2) {
                        mVideoCateListDefault.remove(it)
                    }
                    mVideoFragmentStatePagerAdapter.notifyDataSetChanged()
                    videoCategoryPopup.setFillDataCateListDefault(mVideoCateListDefault)
                }
            }
        })
    }

}